package com.mall.order.config;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.mall.domain.Result;
import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

@Configuration
@Component
public class SentinelException implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        String msg = "";
        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            msg = "被限流了";
        } else if (e instanceof DegradeException) {
            msg = "服务降级了";
        } else if (e instanceof ParamFlowException) {
            msg ="被限流了";
        } else if (e instanceof SystemBlockException) {
            msg ="被系统保护了";
        } else if (e instanceof AuthorityException) {
            msg ="被授权了";
        }

        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(Result.builder().code(1001).message(msg).build());
    }
}

